home *** CD-ROM | disk | FTP | other *** search
- Path: bigblue.oit.unc.edu!mebust
- From: mebust@email.unc.edu (Scott Mebust)
- Newsgroups: comp.lang.c++
- Subject: Sorting pointers to objects with qsort
- Date: 4 Feb 1996 03:15:12 GMT
- Organization: The University of North Carolina at Chapel Hill
- Message-ID: <4f18c0$12do@bigblue.oit.unc.edu>
- NNTP-Posting-Host: login0.email.unc.edu
- X-Newsreader: TIN [version 1.2 PL2]
-
- I'd appreciate any help on the following problem: sorting pointers to
- objects (based on object attributes) using qsort.
-
- If replying, please send an e-mail as well. Thanks.
-
- Scott
- mebust@email.unc.edu
-
-
- // QUESTION: Why does the following code return the wrong results?
-
- // I can't seem to figure this one out. The program below attempts to
- // sort an array of pointers to String objects using qsort. It compiles
- // and may *seem* to return the correct results but does not actually
- // sort the pointers based on any valid data.
-
- // I believe the problem has to do with "qsort" and "const" objects. It
- // appears as though qsort is creating new, const String(s) but the
- // str_ member is not copying correctly.
-
- // This is probably some *elementary* problem but I just can't *see* what
- // is going wrong.
-
- // Any help or advice would be greatly appreciated.
-
-
- #include <string.h>
- #include <iostream.h>
- #include <stdlib.h>
-
- class String
- {
- public:
- String(const char* ccp)
- { str_=new char[strlen(ccp)+1]; strcpy(str_,ccp); }
- ~String()
- { delete [] str_; }
- String (const String& csr)
- { str_=new char[strlen(csr.str_)+1]; strcpy(str_,csr.str_); }
- String& operator= (const String& csr)
- {
- if (this!=&csr)
- {
- delete[] str_;
- str_=new char[strlen(csr.str_)+1];
- strcpy(str_,csr.str_);
- }
- return *this;
- }
- const char * GetValue(void) const
- { return str_; }
- friend ostream& operator<< (ostream& o, String& s);
-
- private:
- char* str_;
- };
-
- ostream& operator<< (ostream& o, String& s)
- {
- return (o << s.str_);
- }
-
- int StrCmpFn (const void* VP1, const void* VP2)
- {
- return strcmp(((const String*)VP1)->GetValue(),
- ((const String*)VP2)->GetValue());
- }
-
- void main (void)
- {
- String A("Apple"), B("Baseball"), C("Chevrolet");
- String* SPA[3] = {&C, &B, &A};
-
- cout << *SPA[0] << endl
- << *SPA[1] << endl
- << *SPA[2] << endl << endl;
-
- qsort(SPA,3,sizeof(SPA[0]),StrCmpFn);
-
- cout << *SPA[0] << endl
- << *SPA[1] << endl
- << *SPA[2] << endl << endl;
- }
-
-
-
-
-
-
-
-
-